package com.lagou.server;

import com.lagou.invoke.RpcRequest;
import com.lagou.invoke.RpcResponse;
import com.lagou.serializer.JSONSerializer;
import com.lagou.serializer.RpcDecoder;
import com.lagou.serializer.RpcEncoder;
import com.lagou.server.handler.NettyInvocationHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import org.I0Itec.zkclient.ZkClient;
import org.apache.commons.lang3.StringUtils;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;

/**
 * @author Kirito
 * @description:
 * @date 2020/05/26
 */
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@MapperScan(basePackages = {"com.lagou.server.dao"})
public class ServerBootstrap implements CommandLineRunner {

    private final Logger log = LoggerFactory.getLogger(ServerBootstrap.class);

    @Value("${rpc.port}")
    private int rpcPort;

    @Autowired
    private ZkClient zkClient;

    public static void main(String[] args) {
        SpringApplication.run(ServerBootstrap.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        io.netty.bootstrap.ServerBootstrap bootstrap = new io.netty.bootstrap.ServerBootstrap();
        bootstrap.group(eventLoopGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel channel) throws Exception {
                        ChannelPipeline pipeline = channel.pipeline();
                        pipeline.addLast(new RpcEncoder(RpcResponse.class, new JSONSerializer()));
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(new NettyInvocationHandler());
                    }
                });
        bootstrap.bind("localhost", rpcPort);

        // Netty启动完成后，将信息注册到zk
        registry("localhost", rpcPort);
    }

    /**
     * 注册Netty服务信息，统一在/servers创建子目录，客户端监听/servers来感知服务端变化
     *
     * @param host String
     * @param port int
     */
    private void registry(String host, int port) {
        String parent = "/servers";
        boolean exists = zkClient.exists(parent);
        if (!exists) {
            zkClient.createPersistent(parent);
        }
        try {
            String subPath = StringUtils.join(new String[]{host, port + ""}, ":");
            zkClient.createEphemeral(StringUtils.join(new String[]{parent, subPath}, "/"));
            log.info("Register success with {}", subPath);
        } catch (Exception e) {
            log.error("Register netty service error: {}", e.getMessage());
        }
    }
}
